package example.conc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 
 * zhu.tan@gmail.com
 * 05-Jan-2010
 */
public class ConditionalVariableEx {
    ReentrantLock lock = new ReentrantLock();
    private String[] names;
    private int MAXLENGTH = 10;
    final Condition notFull = lock.newCondition();
    final Condition notEmpty = lock.newCondition();
    private int putPosition, getPosition, count;

    public ConditionalVariableEx() {
        names = new String[MAXLENGTH];
    }

    public void put(String str) {
        lock.lock();
        try {
            System.out.println("Writer : Array Size : " + count);
            while (count == MAXLENGTH) {
                System.out.println("Writer Waiting");
                notFull.await();
            }
            count++;
            names[putPosition++] = str;
            if (putPosition == MAXLENGTH)
                putPosition = 0;
            Thread.sleep(100);
            notEmpty.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void get() {
        lock.lock();
        try {
            System.out.println("Reader : Array Size : " + count);
            while (count == 0) {
                System.out.println("Reader Waiting");
                notEmpty.await();
            }
            count--;
            names[getPosition++] = null;
            if (getPosition == MAXLENGTH)
                getPosition = 0;
            Thread.sleep(100);
            notFull.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}